﻿using System;
using System.Drawing;
using System.Threading;
using InspectionMAC.Algorithm;
using InspectionMAC.Config;
using csLTDMC;
using InspectionMAC.Function;
using System.IO;
using System.Windows.Forms;
using InspectionMAC.Forms;
using System.Collections.Concurrent;
using MvCameraControl;

namespace InspectionMAC.SystemThread
{
    public class GetCameraImgThread03
    {
        public static Thread CameraImgFlow_Thread = null;
        public static int CameraImgGet_Step = 0;
        public static DateTime imgDateTime;
        public static bool CameraTrigger_Flowrec = false;
        public static string CurrentSampleId { get; set; } = string.Empty;

        // 修改：添加处理统计
        public static int ProcessedCount { get; private set; } = 0;
        public static int FailedCount { get; private set; } = 0;

        public static void CameraImgGet_Thread()
        {
            CameraTrigger_Flowrec = true;
            CameraImgFlow_Thread = new Thread(CameraImgGetThread);
            CameraImgFlow_Thread.IsBackground = true;
            CameraImgFlow_Thread.Start();
            Console.WriteLine("工位3图像处理线程已启动");
        }

        public static void StopThread()
        {
            CameraTrigger_Flowrec = false;
            if (CameraImgFlow_Thread != null && CameraImgFlow_Thread.IsAlive)
            {
                if (!CameraImgFlow_Thread.Join(2000))
                {
                    CameraImgFlow_Thread.Interrupt();
                }
            }
            Console.WriteLine($"工位3线程已停止，处理统计: 成功{ProcessedCount}次, 失败{FailedCount}次");
        }
        public static bool isNG;

        private static void CameraImgGetThread(object obj)
        {
            Console.WriteLine("工位3图像处理线程开始运行");
            ProcessedCount = 0;
            FailedCount = 0;

            while (CameraTrigger_Flowrec)
            {
                try
                {
                    // 修改：从队列获取图像（阻塞式，最多等待100ms）
                    if (CameraReceiveThread_03.ImageQueue.TryTake(out IFrameOut frameOut, 100))
                    {
                        imgDateTime = DateTime.Now;
                        Console.WriteLine($"工位3开始处理图像: {imgDateTime:HH:mm:ss.fff}");
                        isNG = false;
                        using (frameOut) // 使用using确保资源释放
                        {
                            try
                            {
                                var material = MaterialTracker.GetNextPendingMaterial(MaterialTracker.MaterialStatus.Station3Triggered); // 指定状态
                                if (material == null)
                                {
                                    Console.WriteLine("工位3: 无待处理物料，跳过图像处理");
                                    FailedCount++;
                                    continue;
                                }

                                string sampleId = material.Id;
                                CurrentSampleId = sampleId;

                                // 更新物料状态
                                MaterialTracker.UpdateMaterialStatus(sampleId, MaterialTracker.MaterialStatus.WaitingForKickDecision);
                                // 处理图像
                                using (Bitmap image = frameOut.Image.ToBitmap())
                                {
                                    

                                    // 调用算法处理
                                    CameraResult03 cameraResult = new CameraResult03();
                                    SingleItemInfoBuilder.Camera3TotalCounts += 1;

                                    AlgorithmModule.EnqueueImageProcess(image, sampleId, 3, ref cameraResult);

                                    Console.WriteLine($"工位3处理完成: {sampleId}, NG={cameraResult.isNG}");
                                    string str = isNG ? "NG" : "OK";
                                    // 保存图片
                                    string dateFolder = imgDateTime.ToString("yyyyMMdd");
                                    string hourFolder = imgDateTime.ToString("HH");
                                    string relativePath = Path.Combine(@"Image", dateFolder, hourFolder, "Camera3");
                                    string fileName = $"{str}_{SingleItemInfoBuilder.Camera3TotalCounts}_{imgDateTime:yyyyMMdd_HHmmssfff}.jpg";
                                    string fullPath = Path.Combine(Application.StartupPath, relativePath);

                                    if (!Directory.Exists(fullPath))
                                    {
                                        Directory.CreateDirectory(fullPath);
                                    }

                                    string filePath = Path.Combine(fullPath, fileName);
                                    image.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);


                                    ProcessedCount++;
                                }
                            }
                            catch (Exception ex)
                            {
                                FailedCount++;
                                Console.WriteLine($"工位3图像处理异常: {ex.Message}");
                            }
                        }
                    }
                    else
                    {
                        // 队列为空，短暂休眠
                        Thread.Sleep(5);
                    }
                }
                catch (ThreadInterruptedException)
                {
                    Console.WriteLine("工位3线程被中断");
                    break;
                }
                catch (Exception ex)
                {
                    FailedCount++;
                    Console.WriteLine($"工位3线程未处理异常: {ex.Message}");
                    Thread.Sleep(10);
                }
            }

            Console.WriteLine("工位3图像处理线程结束");
        }

        // 修改：添加状态查询方法
        public static string GetStatus()
        {
            return $"工位3: 队列深度={CameraReceiveThread_01.ImageQueue.Count}, 处理={ProcessedCount}, 失败={FailedCount}";
        }
    }
}